package main

import (
	"flag"
	"fmt"
	"gitee.com/viwii/vconf/db/dao"
	"gitee.com/viwii/vconf/module/broadcast"
	"gitee.com/viwii/vconf/module/service"
	"net/http"

	"gitee.com/viwii/vconf/db/conf"
	"gitee.com/viwii/vconf/utils"
	//"fmt"
	"log"
	//"net/http"
	"runtime"

	"github.com/ant0ine/go-json-rest/rest"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)



// makeURL 制作Url
func makeURL(str string) string {
	return "/api/" + str + "/:FuncName"
}


func Lanuch(ipstr string) {

	//proxy := config.NewEtcdProxy(cfg)
	//
	//
	//proxy.DownloadAndWatch("/db_server/db.json", func(data string, err error) {
	//	if err != nil{
	//		fmt.Println(data, err)
	//	}
	//})

	api := rest.NewApi()

	statusMw := &rest.StatusMiddleware{}
	api.Use(statusMw)
	api.Use(rest.DefaultDevStack...)

	//jwtMiddleware := &jwt.JWTMiddleware{
	//	Key:           []byte("min-game-key"),
	//	Realm:         "jwt auth",
	//	Timeout:       time.Hour*5,
	//	MaxRefresh:    time.Second * 5,
	//	Authenticator: auth.AuthenticatorFunc,
	//}
	//
	//api.Use(&rest.IfMiddleware{
	//	Condition: func(request *rest.Request) bool {
	//		return !strings.HasPrefix(request.URL.Path, "/api/auth/")
	//	},
	//
	//	IfTrue: jwtMiddleware,
	//})
	//
	//// 注册业务模块
	//authFunc := auth.NewAuth(jwtMiddleware)

	var svr service.Service
	router, err := rest.MakeRouter(
		//rest.Get(makeURL(authFunc.Path), authFunc.ServeHTTP), 					//认证模块
		//rest.Post(makeURL(authFunc.Path), authFunc.ServeHTTP), 					//认证模块
		rest.Get("/admin/api/v1/apps", svr.ListApps),
		rest.Post("/admin/api/v1/app", svr.CreateApp),
		rest.Delete("/admin/api/v1/app", svr.DeleteApp),
		rest.Get("/admin/api/v1/clusters",svr.Clusters),
		rest.Post("/admin/api/v1/cluster",svr.CreateCluster),
		rest.Delete("/admin/api/v1/cluster",svr.DeleteCluster),
		rest.Get("/admin/api/v1/namespaces",svr.Namespaces),
		rest.Post("/admin/api/v1/namespace",svr.AddNamespaces),
		rest.Post("/admin/api/v1/config",svr.UpdateConfig),					//保存配置
		rest.Get("/admin/api/v1/release/history",svr.ListReleaseHistory), 	//发布列表
		rest.Post("/admin/api/v1/release",svr.ReleaseConfig),				//发布版本
		rest.Delete("/admin/api/v1/namespace",svr.DeleteNamespace),			//删除命名空间
	)

	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)


	broadcast.Svr().StartSvr("")
	fmt.Println("start server")
	log.Fatal(http.ListenAndServe(ipstr, api.MakeHandler()))
}

func main() {
	utils.Version()
	runtime.GOMAXPROCS(runtime.NumCPU()) //running in multicore


	pprofIpStr := flag.String("PprofIp", "",  "pprof ip string!")
	ipStr := flag.String("Config", ":12080",  "pprof ip string!")
	flag.Parse()
	//打开性能监控
	if len(*pprofIpStr) > 0 {
		utils.StartPporfService(*pprofIpStr)
	}

	config:=conf.Config{
		DB: conf.DataBase{
			DriverName:"mysql",
			URL: "root:viwii@(127.0.0.1:3306)/xconf?charset=utf8&parseTime=true&loc=Local",
		},
	}

	if err := dao.Init(&config); err != nil {
		fmt.Println("dao init err",err)
		return
	}

	if err := dao.GetDao().Ping(); err != nil {
		fmt.Println("dao init ping",err)
		return
	}

	Lanuch(*ipStr)
}
